import asyncio
import logging
import sys
import threading
import tkinter
import tkinter as tk
from tkinter import *
from tkinter import ttk, messagebox

# logger_level=logging.WARN
logger_level=logging.DEBUG
logging.basicConfig(stream=sys.stdout, level=logger_level,
                    format='%(asctime)s %(name)s [%(pathname)s line:%(lineno)d] %(levelname)s %(message)s')
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))

from milvus_demo.milvus_demo_remote import MilvusDemoRemote

# 创建主窗口
root = tk.Tk()
root.title("Milvus Demo UI")
root.geometry("1300x900")

milvus_demo_remote = MilvusDemoRemote()
per_page_options = milvus_demo_remote.get_embedding_model_names()
# 需要放在 tk.tk() 代码后面才行
per_page_var = tkinter.StringVar(value=milvus_demo_remote.get_embedding_model_function())

# 创建按钮框架
button_frame = ttk.Frame(root)
button_frame.pack(pady=10)

# 定义按钮列表以便于禁用和启用
buttons = []

def disable_buttons():
    for button in buttons:
        button.config(state=tk.DISABLED)

def enable_buttons():
    for button in buttons:
        button.config(state=tk.NORMAL)

def button_drop_connection():
    """"""
    milvus_demo_remote.drop_connection()
    text_box.insert(tk.END, "删除集合成功\n")

def button_create_connection():
    """"""
    if milvus_demo_remote.has_connection():
        text_box.insert(tk.END, "集合已存在,先删除集合再创建成功\n")
        return
    milvus_demo_remote.create_connection()
    text_box.insert(tk.END, "创建集合成功\n")

def button_insert_data():
    """"""
    milvus_demo_remote.insert_data()
    text_box.insert(tk.END, "插入数据成功\n因为示例的id是固定的,多次插入数据条数是增加了,但是查询不会全部显示\n")

def button_insert_data2():
    """"""
    milvus_demo_remote.insert_data2()
    text_box.insert(tk.END, "插入数据成功\n因为示例的id是固定的,多次插入数据条数是增加了,但是查询不会全部显示\n")

def button_query():
    """"""
    query="When was artificial intelligence founded"
    res=milvus_demo_remote.query_milvus(query)
    text_box.insert(tk.END, f"{str(res)}\n")

def button_clear_data():
    """清除数据按钮的回调函数"""
    from tkinter import messagebox
    # messagebox.showinfo("提示", "请输入查询内容")
    if messagebox.askyesno("确认清除数据", "您确定要清除所有数据吗？"):
        milvus_demo_remote.clear_data()
        text_box.insert(tk.END, "清除数据成功\n")

def button_select_embedding_model():
    """"""
    embedding_model_name = per_page_combobox.get()
    milvus_demo_remote.select_embedding_model(embedding_model_name)
    text_box.insert(tk.END, f"切换模型成功\n")


#处理线程,避免UI卡死
action_thread = None
def button_async_fun(_fun):
    disable_buttons()
    root.update()  # 更新主界面以显示进度
    def async_fun(_fun):
        try:
            _fun()
            """"""
        except Exception as e:
            text_box.insert(tk.END, f"执行失败: {str(e)}\n")
            # 打印完整的异常信息
            import traceback
            traceback.print_exc(file=sys.stderr)
        enable_buttons()

    global action_thread
    if action_thread is None or not action_thread.is_alive():
        action_thread = threading.Thread(target=async_fun,args=(_fun,))
        action_thread.start()
        # 等待线程结束,调用这个函数会阻塞线程,直到线程结束
        # action_thread.join()
        # enable_buttons()
    else:
        enable_buttons()
        messagebox.showwarning("提示", "请等待上一个操作完成")

def button_async_fun2(_fun):
    """改为 button_async_fun"""
    disable_buttons()
    root.update()  # 更新主界面以显示进度
    async def async_fun(_fun):
            try:
                _fun()
                """"""
            except Exception as e:
                text_box.insert(tk.END, f"执行失败: {str(e)}\n")
                # 打印完整的异常信息
                import traceback
                traceback.print_exc(file=sys.stderr)
            enable_buttons()
    asyncio.run(async_fun(_fun))

per_page_combobox = ttk.Combobox(button_frame,style='', width=30,height=4, textvariable=per_page_var, values=per_page_options)
per_page_combobox.pack(side=LEFT)
per_page_combobox.bind("<<ComboboxSelected>>", lambda event: button_async_fun(button_select_embedding_model))
# per_page_combobox.set(per_page_var)
buttons.append(per_page_combobox)

# 添加创建集合按钮
create_collection_button = ttk.Button(button_frame, text="删除集合", command=lambda: button_async_fun(button_drop_connection))
create_collection_button.pack(side=LEFT)
buttons.append(create_collection_button)

create_collection_button = ttk.Button(button_frame, text="创建集合", command=lambda: button_async_fun(button_create_connection))
create_collection_button.pack(side=LEFT)
buttons.append(create_collection_button)

# 添加清除数据按钮
create_collection_button = ttk.Button(button_frame, text="清除数据", command=lambda: button_async_fun(button_clear_data))
create_collection_button.pack(side=LEFT)
buttons.append(create_collection_button)

create_collection_button = ttk.Button(button_frame, text="插入数据", command=lambda: button_async_fun(button_insert_data))
create_collection_button.pack(side=LEFT)
buttons.append(create_collection_button)

create_collection_button = ttk.Button(button_frame, text="插入数据2", command=lambda: button_async_fun(button_insert_data2))
create_collection_button.pack(side=LEFT)
buttons.append(create_collection_button)

create_collection_button = ttk.Button(button_frame, text="查询", command=lambda: button_async_fun(button_query))
create_collection_button.pack(side=LEFT)
buttons.append(create_collection_button)

# 创建框架
button_frame = ttk.Frame(root)
button_frame.pack(fill=X)
# 添加信息标签
info_label = ttk.Label(button_frame, text="调试信息", font=("TkDefaultFont", 10))
info_label.pack(side=LEFT)

create_collection_button = ttk.Button(button_frame, text="清除调试信息", command=lambda: text_box.delete(1.0, tk.END))
create_collection_button.pack(side=RIGHT)
buttons.append(create_collection_button)

text_box_panel = Frame(root)
text_box_panel.pack(fill=BOTH,expand=True)
# 创建多行文本框
from tkinter.scrolledtext import ScrolledText
text_box = ScrolledText(text_box_panel,state=tk.DISABLED, wrap=tk.WORD, height=55, width=170)
text_box.pack(pady=10)

# 运行主循环
root.mainloop()